'''
author:        Wang Chenyang <cy-wang21@mails.tsinghua.edu.cn>
date:          2024-09-23
Copyright © Department of Physics, Tsinghua University. All rights reserved

Convert bibtex format
'''

TYPE_MAP = {
    "preprint": "unpublished"
}

BIBTEX_KEYS = [
    "type", "title", "author", "date",
    "publication", "volume", "issue", "pages",
    "url", "doi", "abstract", "note", "keywords"
]

KEY_MAP = {
    "publication": "journaltitle",
    "issue": "number",
}


def convert_to_bibtex(raw_item: dict) -> str:
    ''' Convert an item dict to bibtex '''
    item = raw_item.copy()
    if "highlight" in item.keys():
        if item["highlight"]:
            if "keywords" in item.keys():
                item["keywords"] += ", #highlight"
            else:
                item["keywords"] = "#highlight"

    if item['type'] in TYPE_MAP.keys():
        bibstr = "@" + TYPE_MAP[item['type']] + "{\n"
    else:
        bibstr = "@" + item['type'] + "{\n"

    for key, value in item.items():
        if key in BIBTEX_KEYS:
            if key in KEY_MAP.keys():
                bibstr += "\t" + KEY_MAP[key] + " = " + "{%s}" % (value) + ",\n"
            elif key == "author":
                author_str = value.replace(", ", " and ")
                bibstr += "\t" + "author = {" + author_str + "},\n"
            elif key == "keywords":
                # value = value.replace("#", "\\#")
                bibstr += "\t" + key + " = " + "{%s}" % (value) + ",\n"
            else:
                bibstr += "\t" + key + " = " + "{%s}" % (value) + ",\n"

    bibstr += "}\n"

    return bibstr


def save_to_bibtex(item_list: list[dict]) -> str:
    ''' Save all items to bibtex string '''
    bibstr = ""
    for item in item_list:
        bibstr += convert_to_bibtex(item)
    return bibstr
